#!/usr/bin/env python
# -*- coding: utf-8 -*-

import configparser
import os
from typing import Dict, Set

class ConfigManager:
    """配置管理器，用于保存和读取漫画的已看和收藏状态"""
    
    def __init__(self, config_file='config.ini'):
        self.config_file = config_file
        self.config = configparser.ConfigParser()
        self.load_config()
    
    def load_config(self):
        """加载配置文件"""
        if os.path.exists(self.config_file):
            try:
                self.config.read(self.config_file, encoding='utf-8')
            except Exception as e:
                print(f"加载配置文件出错: {e}")
                self._create_default_config()
        else:
            self._create_default_config()
    
    def _create_default_config(self):
        """创建默认配置"""
        self.config['VIEWED'] = {}
        self.config['FAVORITES'] = {}
        self.config['SETTINGS'] = {}
        self.save_config()
    
    def save_config(self):
        """保存配置文件"""
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                self.config.write(f)
        except Exception as e:
            print(f"保存配置文件出错: {e}")
    
    def is_viewed(self, file_path: str) -> bool:
        """检查漫画是否已看"""
        return self.config.getboolean('VIEWED', os.path.basename(file_path), fallback=False)
    
    def set_viewed(self, file_path: str, viewed: bool = True):
        """设置漫画已看状态"""
        if 'VIEWED' not in self.config:
            self.config['VIEWED'] = {}
        self.config['VIEWED'][os.path.basename(file_path)] = str(viewed)
        self.save_config()
    
    def is_favorite(self, file_path: str) -> bool:
        """检查漫画是否收藏"""
        return self.config.getboolean('FAVORITES', os.path.basename(file_path), fallback=False)
    
    def set_favorite(self, file_path: str, favorite: bool = True):
        """设置漫画收藏状态"""
        if 'FAVORITES' not in self.config:
            self.config['FAVORITES'] = {}
        self.config['FAVORITES'][os.path.basename(file_path)] = str(favorite)
        self.save_config()
    
    def toggle_viewed(self, file_path: str) -> bool:
        """切换已看状态"""
        current_state = self.is_viewed(file_path)
        new_state = not current_state
        self.set_viewed(file_path, new_state)
        return new_state
    
    def toggle_favorite(self, file_path: str) -> bool:
        """切换收藏状态"""
        current_state = self.is_favorite(file_path)
        new_state = not current_state
        self.set_favorite(file_path, new_state)
        return new_state
    
    def get_viewed_comics(self) -> Set[str]:
        """获取所有已看的漫画"""
        if 'VIEWED' not in self.config:
            return set()
        return {name for name, value in self.config['VIEWED'].items() if value.lower() == 'true'}
    
    def get_favorite_comics(self) -> Set[str]:
        """获取所有收藏的漫画"""
        if 'FAVORITES' not in self.config:
            return set()
        return {name for name, value in self.config['FAVORITES'].items() if value.lower() == 'true'}
    
    def get_last_directory(self) -> str:
        """获取上次选择的漫画目录"""
        if 'SETTINGS' not in self.config:
            return ""
        return self.config.get('SETTINGS', 'last_directory', fallback="")
    
    def set_last_directory(self, directory: str):
        """保存最后选择的漫画目录"""
        if 'SETTINGS' not in self.config:
            self.config['SETTINGS'] = {}
        self.config['SETTINGS']['last_directory'] = directory
        self.save_config()
